package cz.spock.cms.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import cz.spock.cms.entity.Project;
import cz.spock.cms.service.ProjectService;
import cz.spock.core.controller.BaseController;

/**
 * 
 * 
 * @author miso
 *
 */
@Controller
public class ProjectController extends BaseController {

    @Autowired
    private ProjectService pService;
    
    // non-ajax
    
    @RequestMapping(value = "/cms/projects", method = RequestMethod.GET)
    public ModelAndView projects(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("/cms/projects");
        // find all projects for current user
        List<Project> pl = pService.findProjectByOwner(this.getCurrentUser().getId());       
        return new ModelAndView("cms/project/projects", "projects", pl);
    }
    
    @RequestMapping(value = "/cms/project/{id}", method = RequestMethod.GET)
    public ModelAndView project(@PathVariable Long id, HttpServletRequest request, HttpServletResponse response) {
        System.out.println("/cms/project");
        // find project by id
        Project p = pService.getProjectById(id);
        return new ModelAndView("cms/project/project").addObject("project", p);
    }
    
    @RequestMapping(value = "/cms/project/create", method = RequestMethod.GET)
    public String projectCreateGet(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("/cms/project/create get");                
        return "cms/project/create";
    }
    
    @RequestMapping(value = "/cms/project/create", method = RequestMethod.POST)
    public String projectCreatePost(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("/cms/project/create");
        // create project
        try {
            // TODO get owner id from session
            pService.createProject(request.getParameter("owner"), request.getParameter("url"));
        } catch(Exception e) {            
            sendJson(response, pService.errorToJson(e.getMessage(), 0));
            return null;
//            return;
        }
        return "redirect:/cms/projects";
    }
    
    @RequestMapping(value = "/cms/project/delete", method = RequestMethod.POST)
    public String projectDelete(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("/cms/project/delete");
        // delete project
        
        return "cms/projects";
    }
    
    // ajax
    
}
